/*
 * @Author: huangyingli
 * @Date: 2023-02-22 13:53:54
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-22 14:21:42
 * @Description: 用于控制请求时的loading状态的拦截器
 */
import { setStatus } from '../redux/common';
import store from '../redux/index';
import { removeBy, isEmpty } from '../utils/utils';
import { STATUS } from '../config';
// 请求栈, 如果请求栈为空, 则表示所有请求都已完成
let httpStack = [];

let reqInterceptor = undefined;
let resInterceptor = undefined;

function requestHandler(config) {
  if (httpStack.includes('/isLogin')) {
    return Promise.reject();
  }
  httpStack.push(config.url);
  judgement(httpStack);
  return config;
}

function responseHandler(response) {
  httpStack = removeBy(httpStack, response.config.url);
  judgement(httpStack);
  return response;
}

function errorHandler(error) {
  httpStack = removeBy(httpStack, error.config.url);
  judgement(httpStack);
  return Promise.reject(error);
}

function judgement(httpStack) {
  if (isEmpty(httpStack)) {
    store.dispatch(setStatus(STATUS.IDLE));
  } else {
    console.log('还有请求存在', httpStack)
    store.dispatch(setStatus(STATUS.LOADING));
  }
}

// eslint-disable-next-line import/no-anonymous-default-export
export default {
  /**
   *
   * @param {Axios} axios
   */
  install(axios) {
    reqInterceptor = axios.interceptors.request.use(
      requestHandler,
      errorHandler
    );
    resInterceptor = axios.interceptors.response.use(
      responseHandler,
      errorHandler
    );
  },
  uninstall(axios) {
    reqInterceptor && axios.interceptors.request.eject(reqInterceptor);
    resInterceptor && axios.interceptors.request.eject(resInterceptor);
  },
};
